from functools import wraps

from odoo.addons.basic_configuration.config.env_config import switch_env
from fastapi.encoders import jsonable_encoder
from odoo.addons.basic_configuration.functions.common_utils_fc import CommonUtils
from odoo.addons.basic_configuration.functions.rp_redis_utils import RedisUtils
from ..functions.logger import log

from werkzeug.utils import redirect


class PayException(Exception):
    def __init__(self, msg):
        self.msg = msg


class AuthException(Exception):
    """
    验证异常
    """

    def __init__(self, msg, code, **kwargs):
        self.msg = msg
        self.code = code


def exception_handler(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            response = func(self, *args, **kwargs)
            return response
        except PayException as e:
            # 生成随机序列
            md5_hex = CommonUtils().gene_random_sequence()
            # 获取Redis客户端
            redis_client = RedisUtils()
            redis_client.add_str(md5_hex, e.msg)
            log('Redis键是：{}'.format(md5_hex))
            response = redirect('{}?error={}'.format(switch_env['h5_url']['url'], md5_hex))
            return response

    return wrapper


def auth_exception_handler(func):
    @wraps(func)
    async def wrapper(self=None, *args, **kwargs):
        try:
            response = await func(self, *args, **kwargs)
            return response
        except AuthException as e:
            return jsonable_encoder({
                'msg': e.msg,
                'code': e.code
            })

    return wrapper
